import type UserRole from "../vite-env.d";
import {HttpService} from "./Http.ts";
import {JOB_SEEKER_ROLE} from "../vite-env.d";

export type StorageItem =  {
    data: any,
    expiration?: number,
    other?: any
}

class LocalStorage {
    private readonly interval: number = 5 * 60 * 1000;
    private readonly TOKEN_KEY = "token";
    private readonly INTERVAL_ID_KEY: string = "INTERVAL_ID_KEY";
    constructor(interval?: number) {
        this.clearLastInterval();
        if (interval) {
            this.interval = interval;
        }
        this.initInterval();
    }
    private initInterval() {
        let intervalId = setInterval(this.clearTimeOutItem, this.interval);
        console.log("Create Interval", intervalId);
        this.setItem(this.INTERVAL_ID_KEY, {data: intervalId});
    }
    private clearLastInterval() {
        let intervalItem = localStorage.getItem(this.INTERVAL_ID_KEY) as unknown as StorageItem;
        if (intervalItem) {
            console.log("Clear Last Interval", intervalItem);
            clearInterval(intervalItem.data);
        }
    }
    private clearTimeOutItem() {
        for (let i=0; i<localStorage.length; i++) {
            let key = localStorage.key(i);
            if (key) {
                let jsonItem = localStorage.getItem(key)
                if (jsonItem) {
                    let item = (JSON.parse(jsonItem)) as StorageItem;
                    if (item.expiration && item.expiration < new Date().getTime()) {
                        localStorage.removeItem(key);
                    }
                } else {
                    localStorage.removeItem(key);
                }
            }
        }
    }
    public async changeUser(role: UserRole) {
        let ret;
        if (role === JOB_SEEKER_ROLE) {
            ret = await HttpService.get("/jobSeeker/testUser")
        } else {
            ret = await HttpService.get("/recruiter/testUser")
        }
        this.setItem("currentUser", {data: ret.data})
        this.setItem("userType", {data: role})
    }
    public async getCurrentUser() {
        const type = this.getItem('userType')?.data
        const user = this.getItem('currentUser')?.data
        return {type: type, user: user}
    }
    public setToken = (token: string, other?: {}) => {
        this.setItem(this.TOKEN_KEY, {data: token, other: other});
    };
    public getToken = (): StorageItem | null => {
        return this.getItem(this.TOKEN_KEY);
    };
    public setItem = (key:string, item: StorageItem) => {
        localStorage.setItem(key, JSON.stringify(item));
    };
    public getItem = (key:string): StorageItem | null => {
        let jsonItem = localStorage.getItem(key);
        return jsonItem ? JSON.parse(jsonItem) as StorageItem : null;
    };
}

export const LocalStorageUtil = new LocalStorage();